#!/bin/bash

# Copyright 2023 The gVisor Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -euxo pipefail

# expected_regex is generated by running `iptables -t nat -S` inside a runc
# Docker container connected to a custom network. Custom networks cause Docker
# to install DNS routing rules.
expected_regex='-P PREROUTING ACCEPT
-P INPUT ACCEPT
-P OUTPUT ACCEPT
-P POSTROUTING ACCEPT
-N DOCKER_OUTPUT
-N DOCKER_POSTROUTING
-A OUTPUT -d 127.0.0.11/32 -j DOCKER_OUTPUT
-A POSTROUTING -d 127.0.0.11/32 -j DOCKER_POSTROUTING
-A DOCKER_OUTPUT -d 127.0.0.11/32 -p tcp -m tcp --dport 53 -j DNAT (--to-destination 127.0.0.11:[0-9]+|\[unsupported revision\])
-A DOCKER_OUTPUT -d 127.0.0.11/32 -p udp -m udp --dport 53 -j DNAT (--to-destination 127.0.0.11:[0-9]+|\[unsupported revision\])
-A DOCKER_POSTROUTING -s 127.0.0.11/32 -p tcp -m tcp --sport [0-9]+ -j SNAT --to-source :53
-A DOCKER_POSTROUTING -s 127.0.0.11/32 -p udp -m udp --sport [0-9]+ -j SNAT --to-source :53'

# The runtime name is the first and only argument.
runtime="$1"

# The image passed to docker run uses iptables-nft by default, so the above
# rules can't be simply scraped and passed to gVisor. We test that those rules
# are correctly translated to iptables-legacy rules.
net_name="nftables-test-net-$(shuf -i 0-99999999 -n 1)"
docker network create "$net_name"
trap "docker network rm \"$net_name\"" EXIT
got=$(docker run --network="$net_name" --rm --runtime "$runtime" --privileged gvisor.dev/images/iptables iptables-legacy -t nat -S)
if ! [[ "$got" =~ $expected_regex ]]; then
  echo "Got incorrect rules: got on the left, want on the right"
  diff <(echo "$got") <(echo "$expected_regex")
  exit 1
fi
